<template>
  <div class="chart-container">
    <div class="chart-content" :style="{ height: chartHeight }">
      <div 
        :id="chartId" 
        class="chart" 
        ref="chartRef"
      ></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'

interface Props {
  chartId: string
  chartHeight?: string
  options?: any
}

interface Emits {
  (e: 'chartReady', chart: echarts.ECharts): void
}

const props = withDefaults(defineProps<Props>(), {
  chartHeight: '300px'
})

const emit = defineEmits<Emits>()

const chartRef = ref<HTMLElement>()
let chart: echarts.ECharts | null = null

const initChart = async () => {
  await nextTick()
  
  const element = document.getElementById(props.chartId)
  if (!element) return
  
  if (chart) {
    chart.dispose()
  }
  
  chart = echarts.init(element, 'dark')
  
  if (props.options) {
    chart.setOption(props.options)
  }
  
  // 添加多种响应式监听
  const handleResize = () => {
    setTimeout(() => {
      chart?.resize()
    }, 100)
  }
  
  // 窗口大小变化
  window.addEventListener('resize', handleResize)
  
  // 使用 ResizeObserver 监听容器大小变化
  let resizeObserver: ResizeObserver | null = null
  if (window.ResizeObserver) {
    resizeObserver = new ResizeObserver(() => {
      handleResize()
    })
    resizeObserver.observe(element)
  }
  
  // 存储清理函数
  const cleanup = () => {
    window.removeEventListener('resize', handleResize)
    resizeObserver?.disconnect()
  }
  
  // 将清理函数存储在图表实例上
  ;(chart as any)._cleanup = cleanup
  
  emit('chartReady', chart)
}

watch(() => props.options, (newOptions) => {
  if (chart && newOptions) {
    chart.setOption(newOptions, true)
  }
}, { deep: true })

onMounted(() => {
  // 延迟初始化确保DOM完全渲染
  setTimeout(() => {
    initChart()
  }, 100)
})

onUnmounted(() => {
  if (chart) {
    // 调用存储的清理函数
    ;(chart as any)._cleanup?.()
    chart.dispose()
    chart = null
  }
})

defineExpose({
  chart: () => chart
})
</script>

<style scoped>
.chart-container {
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(0, 212, 255, 0.3);
  border-radius: 12px;
  padding: 15px;
  height: 100%;
}

.chart-content {
  height: 100%;
}

.chart {
  width: 100%;
  height: 100%;
}
</style>
